package com.firebird.app.reader.pdf.activity

import android.Manifest
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.DownloadManager
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.database.ContentObserver
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.firebird.app.reader.R
import com.firebird.app.reader.pdf.util.Constants
import com.firebird.app.reader.pdf.util.PDFUtil
import com.firebird.app.reader.pdf.util.PDFUtil.toUtf8String
import com.tbruyelle.rxpermissions2.Permission
import com.tbruyelle.rxpermissions2.RxPermissions
import com.tencent.smtt.sdk.TbsReaderView
import io.reactivex.functions.Consumer
import java.io.File

/**
 * @作者: njb
 * @时间: 2019/9/11 20:31
 * @描述: pdf文件预览
 */
class PDFPreViewActivity : AppCompatActivity(), TbsReaderView.ReaderCallback {
    private var mTbsReaderView: TbsReaderView? = null
    private var mFileName: String? = null
    private var tv_download: TextView? = null
    private var mRequestId: Long = 0
    private var mDownloadObserver: DownloadObserver? = null
    private var progressBar_download: ProgressBar? = null
    private var mDownloadManager: DownloadManager? = null
    private var fileName: String? = null
    private var fileUrl: String? = null
    private val TAG = PDFPreViewActivity::class.java.simpleName
    private var rootRl: RelativeLayout? = null
    private var tv_title: TextView? = null
    private var iv_back: ImageView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_pdf_preview)
        initIntent()
        initTbsReaderView()
        mTbsReaderView = TbsReaderView(this, this)
        rootRl!!.addView(mTbsReaderView, RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT))
        if (fileUrl == null || fileUrl!!.length <= 0) {
            Toast.makeText(this@PDFPreViewActivity, "获取文件url出错了", Toast.LENGTH_SHORT).show()
            return
        }
        mFileName = PDFUtil.parseName(fileUrl!!)
        requestPermission()
        isDown
    }

    private fun initIntent() {
        if (getIntent() != null && getIntent().getExtras() != null) {
            fileUrl = getIntent().getExtras().getString("fileUrl")
            fileName = getIntent().getExtras().getString("fileName")
        }
    }

    //初始化TbsReaderView 5-3
    private fun initTbsReaderView() {
        rootRl = findViewById(R.id.rl_tbsView)
        tv_download = findViewById(R.id.tv_download)
        progressBar_download = findViewById(R.id.progressBar_download)
        tv_title = findViewById(R.id.tv_title)
        tv_title!!.text = "PDF文件预览"
        iv_back = findViewById(R.id.iv_back)
        iv_back!!.setOnClickListener { finish() }
    }

    private fun requestPermission() {
        val rxPermissions = RxPermissions(this)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            rxPermissions.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                    .subscribe(object : Consumer<Permission?>() {
                        fun accept(permission: Permission) {
                            if (permission.granted) { // 用户已经同意该权限
                                Log.d(TAG, permission.name.toString() + " is granted.")
                            } else if (permission.shouldShowRequestPermissionRationale) { // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                                Log.d(TAG, permission.name.toString() + " is denied. More info should be provided.")
                            } else { // 用户拒绝了该权限，并且选中『不再询问』
                                Log.d(TAG, permission.name.toString() + " is denied.")
                            }
                        }
                    })
        }
    }

    private val isDown: Unit
        private get() {
            if (isLocalExist || fileUrl!!.contains("storage")) {
                tv_download!!.text = "打开文件"
                tv_download!!.visibility = View.GONE
                displayFile()
            } else {
                if (!fileUrl!!.contains("http")) {
                    AlertDialog.Builder(this@PDFPreViewActivity)
                            .setTitle("温馨提示:")
                            .setMessage("文件的url地址不合法哟，无法进行下载")
                            .setCancelable(false)
                            .setPositiveButton("确定", DialogInterface.OnClickListener { dialog, which -> return@OnClickListener }).create().show()
                }
                startDownload()
            }
        }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    private fun queryDownloadStatus() {
        val query = DownloadManager.Query()
                .setFilterById(mRequestId)
        var cursor: Cursor? = null
        try {
            cursor = mDownloadManager!!.query(query)
            if (cursor != null && cursor.moveToFirst()) { // 已经下载的字节数
                val currentBytes = cursor
                        .getLong(cursor
                                .getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
                // 总需下载的字节数
                val totalBytes = cursor
                        .getLong(cursor
                                .getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
                // 状态所在的列索引
                val status = cursor.getInt(cursor
                        .getColumnIndex(DownloadManager.COLUMN_STATUS))
                tv_download!!.text = "下载中...(" + PDFUtil.FormetFileSize(currentBytes)
                        .toString() + "/" + PDFUtil.FormetFileSize(totalBytes).toString() + ")"
                // 将当前下载的字节数转化为进度位置
                val progress = (currentBytes * 1.0 / totalBytes * 100).toInt()
                progressBar_download!!.progress = progress
                Log.i("downloadUpdate: ", currentBytes.toString() + " " + totalBytes + " "
                        + status + " " + progress)
                if (DownloadManager.STATUS_SUCCESSFUL == status
                        && tv_download!!.visibility == View.VISIBLE) {
                    tv_download!!.visibility = View.GONE
                    tv_download!!.performClick()
                    if (isLocalExist) {
                        tv_download!!.visibility = View.GONE
                        progressBar_download!!.visibility = View.GONE
                        displayFile()
                    }
                }
            }
        } finally {
            cursor?.close()
        }
    }

    /**
     * 加载显示文件内容
     */
    private fun displayFile() {
        val bundle = Bundle()
        if (isLocalExist) {
            bundle.putString("filePath", localFile.path)
        }
        if (fileUrl!!.contains("storage")) {
            bundle.putString("filePath", fileUrl)
        }
        bundle.putString("tempPath", Environment.getExternalStorageDirectory().path)
        val result: Boolean = mTbsReaderView.preOpen(PDFUtil.getFileType(mFileName!!), false)
        if (result) {
            mTbsReaderView.openFile(bundle)
        } else {
            val file = File(localFile.path)
            if (file.exists()) {
                val openintent = Intent()
                openintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                val type: String = PDFUtil.getMIMEType(file)
                // 设置intent的data和Type属性。
                openintent.setDataAndType(Uri.fromFile(file), type)
                // 跳转
                startActivity(openintent)
                finish()
            }
        }
    }

    /**
     * 下载文件
     */
    @SuppressLint("NewApi")
    private fun startDownload() {
        mDownloadObserver = DownloadObserver(Handler())
        getContentResolver().registerContentObserver(
                Uri.parse("content://downloads/my_downloads"), true,
                mDownloadObserver!!)
        mDownloadManager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager?
        //将含有中文的url进行encode
        val mFileUrl: String = toUtf8String(fileUrl!!)
        try {
            val request = DownloadManager.Request(
                    Uri.parse(mFileUrl))
            request.setDestinationInExternalPublicDir(Constants.DOWNLOAD_PDF_PATH, mFileName)
            request.allowScanningByMediaScanner()
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN)
            mRequestId = mDownloadManager!!.enqueue(request)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 是否为本地文件
     *
     * @return
     */
    private val isLocalExist: Boolean
        private get() = localFile.exists()

    /**
     * 本地文件目录
     *
     * @return
     */
    private val localFile: File
        private get() = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), mFileName!!)

    override fun onCallBackAction(integer: Int?, o: Any?, o1: Any?) {}
    private inner class DownloadObserver constructor(handler: Handler) : ContentObserver(handler) {
        override fun onChange(selfChange: Boolean, uri: Uri) {
            queryDownloadStatus()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mTbsReaderView?.onStop()
        if (mDownloadObserver != null) {
            getContentResolver().unregisterContentObserver(mDownloadObserver)
        }
    }

    companion object {
        /**
         * 跳转页面
         *
         * @param context
         * @param fileUrl  文件url
         * @param fileName 文件名
         */
        fun actionStart(context: Context, fileUrl: String?, fileName: String?) {
            val intent = Intent(context, PDFPreViewActivity::class.java)
            intent.putExtra("fileUrl", fileUrl)
            intent.putExtra("fileName", fileName)
            context.startActivity(intent)
        }
    }
}
